package com.wmh.baseservice.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.redis.config.RedisConfig;
import com.wmh.baseservice.common.redis.utils.RedisUtil;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.system.pojo.SysChat;
import com.wmh.baseservice.system.pojo.vo.ChatVo;
import com.wmh.baseservice.system.pojo.vo.MsgListVo;
import com.wmh.baseservice.system.service.SysChatService;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "用户端-聊天消息相关接口")
@RestController
@RequestMapping(value = "user/sysChat", produces = "text/plain;charset=utf-8")
@RequiresRoles("user")
public class UsChatController {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private SysChatService sysChatService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private MerchantInfoService merchantInfoService;

    @ApiOperation("聊天列表")
    @PostMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String list() {
        Long usId = (Long) request.getAttribute("usId");
        Map<String, Object> map = new HashMap<>();
        map.put("type", "user");
        map.put("uid", usId);
        List<MsgListVo> msgListVos = new ArrayList<>();


        List<SysChat> sysChats = sysChatService.getList(map);
//        String suffix = usId + ":*";
//        String keys = RedisConfig.KEY_INFO + "CHAT-" + suffix;
//        Set<String> keysList = redisUtil.keys(keys);
//        keysList.forEach();


        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        sysChats.forEach(item -> {
            MsgListVo msgListVo = new MsgListVo();
            MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(item.getSendType() == 1 ? item.getSendId() : item.getUid());
            if (CommUtil.checkNull(merchantInfo)) {
                msgListVo.setAvatar(merchantInfo.getStoreAvatar());
                switch (item.getMsgType()) {
                    case "voice":
                        msgListVo.setContent("<font style='color: #3498db;'>【语音消息】<font/>");
                        break;
                    case "image":
                        msgListVo.setContent("<font style='color: #1abc9c;'>【图片】<font/>");
                        break;
                    case "redEnvelope":
                        msgListVo.setContent("<font style='color: #ff6348;'>【有红包】<font/>");
                        break;
                    default:
                        msgListVo.setContent(item.getContent());
                        break;
                }
                msgListVo.setTime(format.format(item.getCreateTime()));
                msgListVo.setTitle(merchantInfo.getStoreName());
                msgListVo.setId(item.getUid());
                msgListVo.setSendId(item.getSendId());
                msgListVo.setType(item.getType());
                msgListVos.add(msgListVo);
            }
        });
        return ReturnBody.success(msgListVos);
    }

    @ApiOperation("获取聊天记录")
    @PostMapping("getMsgList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "merchantId", value = "商家id", required = true),
    })
    public String getMsgList(Long merchantId) {
        Long id = (Long) request.getAttribute("usId");
        String suffix = id + ":" + merchantId;
        String key = RedisConfig.KEY_INFO + "CHAT-" + suffix;

        if (redisUtil.hasKey(key)) {
            List<SysChat> sysChats = (List<SysChat>) redisUtil.get(key);
            //标注已读,定时任务凌晨回写数据库
            sysChats.forEach(item -> item.setStatus(1));
            redisUtil.set(key, sysChats);
            //处理数据格式
            return ReturnBody.success(conversion(sysChats));
        } else {
            //查询数据库
            List<SysChat> sysChats = sysChatService.listForUpdate(new QueryWrapper<SysChat>().eq(SysChat.SESSION_ID, suffix));
            sysChats.forEach(item -> item.setStatus(1));
            //修改数据库
//            if (!sysChatService.updateBatchById(sysChats)) {
//                throw new ServiceException("回写状态异常");
//            }
            //缓存进redis
            redisUtil.set(key, sysChats);
            return ReturnBody.success(conversion(sysChats));
        }
    }


    private List<ChatVo> conversion(List<SysChat> sysChats) {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        List<ChatVo> chatVoList = new ArrayList<>();
        for (SysChat sysChat : sysChats) {
            ChatVo chatVo = new ChatVo();
            JSONObject object = new JSONObject(true);
            object.put("id", sysChat.getId());
            object.put("type", sysChat.getMsgType());
            object.put("time", format.format(sysChat.getCreateTime()));
            object.put("sendType", sysChat.getType());
            JSONObject infoObj = new JSONObject(true);
            infoObj.put("uid", sysChat.getUid());
            if ("user".equals(sysChat.getType())) {
                UsInfo usInfo = usInfoService.getByIdForUpdate(sysChat.getUid());
                infoObj.put("username", usInfo.getNick());
                infoObj.put("face", usInfo.getAvatar());
            } else if ("merchant".equals(sysChat.getType())) {
                MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(sysChat.getUid());
                infoObj.put("username", merchantInfo.getStoreName());
                infoObj.put("face", merchantInfo.getStoreAvatar());
            }
            object.put("userinfo", infoObj);
            infoObj = new JSONObject(true);
            infoObj.put("text", sysChat.getContent());
            switch (sysChat.getMsgType()) {
                case "image":
                    infoObj.put("w", sysChat.getW());
                    infoObj.put("h", sysChat.getH());
                    break;
                case "voice":
                    infoObj.put("length", sysChat.getLength());
                    break;
                case "redEnvelope":
                    infoObj.put("blessing", sysChat.getContent());
                    infoObj.put("rid", sysChat.getRid());
                    infoObj.put("isReceived", sysChat.getHasReceived() == 1);
                    break;
            }
            object.put("content", infoObj);
            chatVo.setType("user");
            chatVo.setMsg(object);
            chatVoList.add(chatVo);
        }
        return chatVoList;
    }


}
